package org.example.codeservce.config;

import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig
{

    /**
     * 创建线程池
     *
     * @return ThreadPoolExecutor 线程池
     */
    @Bean
    public ThreadPoolExecutor taskExecutor()
    {
        // 核心线程数为CPU核心数加1
        int corePoolSize = 16 + 1;
        // 最大线程数为核心线程数的2倍
        int maximumPoolSize = corePoolSize * 2;
        // 线程空闲时间为60秒
        long keepAliveTime = 60;
        TimeUnit unit = TimeUnit.SECONDS;
        // 使用有界队列，大小为100
        ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(100);
        // 创建线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                workQueue
        );
        // 拒绝策略为默认的AbortPolicy
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        return executor;
    }

    /**
     * 文件上传配置
     * @return
     */
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大
        factory.setMaxFileSize(DataSize.parse("300MB"));
        //KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("300MB"));
        return factory.createMultipartConfig();
    }

}
